package com.example.li_han.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "FileUploadServlet", value = "/FileUploadServlet")
@MultipartConfig(
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50    // 50MB
)
public class FileUploadServlet extends HttpServlet {
    // 使用绝对外部路径，不受Tomcat部署影响
    private static final String EXTERNAL_UPLOAD_BASE = "D:/lihan_uploads";
    private static final String UPLOAD_SUB_DIR = "images";
    private String uploadBasePath;

    @Override
    public void init() throws ServletException {
        // 使用绝对外部路径
        uploadBasePath = EXTERNAL_UPLOAD_BASE + File.separator + UPLOAD_SUB_DIR;

        File uploadDir = new File(uploadBasePath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            System.out.println("==========================================");
            System.out.println("外部文件上传目录初始化:");
            System.out.println("目录路径: " + uploadBasePath);
            System.out.println("创建结果: " + (created ? "成功" : "失败"));
            System.out.println("==========================================");
        } else {
            System.out.println("==========================================");
            System.out.println("外部文件上传目录已存在: " + uploadBasePath);
            System.out.println("==========================================");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");

        try {
            Part filePart = request.getPart("file");
            if (filePart == null || filePart.getSize() == 0) {
                response.getWriter().write("{\"code\":500,\"msg\":\"未获取到上传文件\"}");
                return;
            }

            String originalFileName = getFileName(filePart);
            System.out.println("收到上传文件: " + originalFileName);

            String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + suffix;

            // 保存到外部目录
            String filePath = uploadBasePath + File.separator + newFileName;
            filePart.write(filePath);

            File savedFile = new File(filePath);
            System.out.println("文件保存到外部目录:");
            System.out.println("保存路径: " + filePath);
            System.out.println("文件大小: " + savedFile.length() + " bytes");
            System.out.println("文件存在: " + savedFile.exists());

            // 返回相对路径（需要通过新的Servlet访问）
            String relativePath = "external_images/" + newFileName;
            response.getWriter().write("{\"code\":200,\"fileName\":\"" + relativePath + "\",\"msg\":\"上传成功\"}");

        } catch (Exception e) {
            System.err.println("文件上传失败:");
            e.printStackTrace();
            response.getWriter().write("{\"code\":500,\"msg\":\"上传失败：" + e.getMessage() + "\"}");
        }
    }

    // 获取上传文件的真实文件名
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] tokens = contentDisposition.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length() - 1);
            }
        }
        return "unknown";
    }
}